import configparser
import platform
import os
import json
import re
import polib


def find_files(directory):
    """
    递归遍历指定目录及其子目录中的所有文件，并返回所有文件的路径。
    忽略以点(.)开头的文件或目录。
    """
    for root, dirs, files in os.walk(directory):
        files = [f for f in files if not f[0] == '.']
        dirs[:] = [d for d in dirs if not d[0] == '.']
        for file in files:
            yield os.path.join(root, file)

def contains_chinese_characters(str):
    """
    检查一个字符串是否包含中文字符。
    """
    return bool(re.search('[\u4e00-\u9fff]', str))

def recursive_iter(obj):
    """
    递归遍历一个对象中所有的键值对。
    """
    if isinstance(obj, dict):
        for key, value in obj.items():
            yield from recursive_iter(value)
    elif any(isinstance(obj, t) for t in (list, tuple)):
        for value in obj:
            yield from recursive_iter(value)
    else:
        yield obj

def add_to_po_file(value, po_path):
    """
    将值添加到指定的PO文件中。
    """
    # 加载PO文件
    po = polib.pofile(po_path)

    # 如果msgid已存在，跳过
    if any(entry.msgid == value for entry in po):
        return

    # 添加新的条目
    entry = polib.POEntry(
        msgid=value,
        msgstr=''
    )
    po.append(entry)

    # 保存PO文件
    po.save(po_path)
    print(f'Added: {value}')


import csv

def process_files(directories, po_paths):
    """
    遍历所有指定的目录，并处理每个文件。只处理可以解析为JSON或CSV的文件。
    """
    for path in directories:
        if os.path.isdir(path):
            for sub_path in os.listdir(path):
                process_files([os.path.join(path, sub_path)], po_paths)
        elif os.path.isfile(path):
            if path.endswith('.csv'):
                try:
                    with open(path, 'r', encoding='utf-8') as file:
                        csv_reader = csv.reader(file)
                        for row in csv_reader:
                            for cell in row:
                                if contains_chinese_characters(cell):
                                    for po_path in po_paths:
                                        add_to_po_file(cell, po_path)
                except ValueError:
                    print(ValueError)
                    continue
            elif path.endswith('.dat') or path.endswith('.config'):
                try:
                    with open(path, 'r', encoding='utf-8') as file:
                        data = json.load(file)
                    for value in recursive_iter(data):
                        if isinstance(value, str) and contains_chinese_characters(value):
                            for po_path in po_paths:
                                add_to_po_file(value, po_path)
                except ValueError:
                    print(ValueError)
                    continue  # 如果文件不能被解析



config = configparser.ConfigParser()

if platform.machine().startswith('arm') and platform.system() == 'Linux':
    config.read('/home/pi/MindSCADA/runtime.ini',encoding='utf-8')
else:
    config.read('C:/mindteco/MindSCADA/runtime.ini',encoding='utf-8')

# server 路径
serverPath = config.get('General', 'CurrentProjectPath')

cpro_config_path = r'C:\Users\jan\AppData\Roaming\Mindteco\app_userdata\Cpro'

directories = [
    os.path.join(serverPath,'Alarm'),
            #    os.path.join(serverPath,'RTDB'),
            #    os.path.join(serverPath,'conf'),
            #    cpro_config_path
               ]  # 你可以添加或修改目录

# 指定要遍历的.po文件的目录
po_directory = "C:\\Users\\jan\\Documents\\Project\\CproScada\\cpro_scada\\dist\\translations\\"  # 当前目录下的po文件夹


po_paths = []
# 遍历指定目录下的所有文件
for file in os.listdir(po_directory):
    filename = os.fsdecode(file)
    # 如果文件是.po文件
    if filename.endswith('.po'):
        po_paths.append(os.path.join(po_directory,filename))

process_files(directories, po_paths)
